package cn.jhc.teachingquality.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;

import java.net.CookieHandler;
import java.net.CookieManager;

import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.R;
import cn.jhc.teachingquality.bean.PracticeLog;
import cn.jhc.teachingquality.bean.TeachingLog;
import cn.jhc.teachingquality.fragment.MainFragment;
import cn.jhc.teachingquality.fragment.PracticeLogFragment;
import cn.jhc.teachingquality.fragment.TeachingLogFragment;
import cn.jhc.teachingquality.rx.RxBus;
import cn.jhc.teachingquality.util.AuthUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;

import static cn.jhc.teachingquality.Global.*;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //enable vm-wide cookie management
        CookieHandler.setDefault(new CookieManager());

//        getSupportFragmentManager().enableDebugLogging(true);

        //check if username and password is saved in preference
        SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFERENCES, 0);
        boolean hasLoggedIn = preferences.getBoolean(PREF_LOGIN_SUCCESS_FLAG, false);
        if(hasLoggedIn){
            String username = preferences.getString(PREF_USERNAME, null);
            String password = preferences.getString(PREF_PASSWORD, null);
            AuthUtils.performLogin(this, username, password);
        } else {
            jumpToLoginActivity();
            return;
        }

        //后台登录成功后再添加MainFragment，并审核所有教学日志。
        RxBus.getInstance().take(String.class)
                .filter(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        return s.equals(Global.LOGIN_SUCCEED_IN_BACKGROUND);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        //设置起始Fragment
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.main_container, new MainFragment(), "main")
                                .addToBackStack("main")
                                .commit();
                    }
                });

//        //审核所有教学日志
//        new VerifyTeachingLogTask(this).execute();

        //接收到实习日志消息时，用实习日志Fragment替换当前界面。
        RxBus.getInstance().take(PracticeLog.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PracticeLog>() {
                    @Override
                    public void call(PracticeLog practiceLog) {
                        PracticeLogFragment fragment = new PracticeLogFragment();
                        Bundle args = new Bundle();
                        args.putSerializable(Global.CURRENT_PRACTICE_LOG, practiceLog);
                        fragment.setArguments(args);
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.main_container, fragment, fragment.toString())
                                .addToBackStack(fragment.toString())
                                .commit();
                    }
                });
        //接收到教学日志消息时，用教学日志Fragment替换当前界面
        RxBus.getInstance().take(TeachingLog.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TeachingLog>() {
                    @Override
                    public void call(TeachingLog teachingLog) {
                        TeachingLogFragment fragment = new TeachingLogFragment();
                        Bundle args = new Bundle();
                        args.putSerializable(Global.CURRENT_TEACHING_LOG, teachingLog);
                        fragment.setArguments(args);
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.main_container, fragment, fragment.toString())
                                .addToBackStack(fragment.toString())
                                .commit();
                    }
                });
    }

    private void jumpToLoginActivity() {
        // Jump to LoginActivity
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
    }

}
